package com.box.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;























import com.box.entity.DbAdmin;
import com.box.entity.DbAdminExample;
import com.box.entity.DbAdminExample.Criteria;
import com.box.entity.DbAdminlog;
import com.box.entity.DbRoles;
import com.box.entity.DbRolesExample;
import com.box.entity.Menu;
import com.box.entity.ResultAdminLog;
import com.box.mapper.DbAdminAndDbAdminlogMapper;
import com.box.mapper.DbAdminMapper;
import com.box.mapper.DbAdminlogMapper;
import com.box.realm.MyRealm;
import com.box.service.AdminService;
import com.box.service.RolesService;
import com.box.utils.CookieUtils;
import com.box.utils.JsonUtils;
import com.box.utils.LayuiResult;
import com.box.utils.ResponseResult;
import com.box.utils.SessionUtils;
import com.box.utils.SystemInfo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;




/**
*<p>Title:AdminServiceImpl.java</p>
*<p>Description:管理员登录注册</p>
*<p>Company:www.99weixinxcx.cn</p>
*@author 陕西电子科技学院:滕一帆
*@date	2019年4月6日下午9:37:05
*@version 1.0
*
*
*
 */
@Service
public class AdminServiceImpl implements AdminService {
	
	
	@Autowired
	private	DbAdminMapper admapper;
	
	@Autowired
	private DbAdminlogMapper adlogMapper;
	
	@Autowired
	private DbAdminAndDbAdminlogMapper ManagerMapper;
	
	@Autowired
	private RolesService roleService;
	
	@Resource
	private MyRealm realm;
	
	
	
	@Value("${USERNAME}")
	private String USERNAME;

	public List<DbAdmin> login(String username, String password) {
		// TODO Auto-generated method stub
		//通过条件进行查询，比对用户名，再查询密码
		if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
			throw new UnknownAccountException("用户名或密码不能为空!");
		}
		// 查询用户信息
		DbAdminExample example = new DbAdminExample();
		Criteria criteria = example.createCriteria();
		criteria.andUsernameEqualTo(username);
		List<DbAdmin> admins = admapper.selectByExample(example);
		// 账号不存在
		if (admins == null || admins.size() == 0) {
			throw new UnknownAccountException("账号不存在!");
		}
		//password = new Md5Hash(password).toString();
		// 密码错误
		if (!password.equals(admins.get(0).getPassword())) {
			throw new IncorrectCredentialsException("账号或密码不正确!");
		}

		// 账号未分配角色
		if (admins.get(0).getRoleId() == null || admins.get(0).getRoleId() == 0) {
			throw new UnknownAccountException("账号未分配角色!");
		}
		
		
		return admins;
	}

	public ResponseResult register(DbAdmin admin) {
		// TODO Auto-generated method stub
		//用户名和密码校验
		System.out.println("我进到注册业务里了"+admin.getUsername()+">>>>>"+admin.getPassword());
		if(StringUtils.isBlank(admin.getUsername())||StringUtils.isBlank(admin.getPassword())){
			
			return ResponseResult.build(600,"用户名或密码不能为空");
			
		}
		System.out.println("我进到注册业务里了2"+admin.getUsername()+">>>>>"+admin.getPassword());
	//查重复,先从数据库里查询,然后进行对比。如果存在就是重复
		DbAdminExample example=new DbAdminExample();
		 Criteria createCriteria = example.createCriteria();
		 createCriteria .andUsernameEqualTo(admin.getUsername());
		List<DbAdmin> list = admapper.selectByExample(example);
		for (DbAdmin dbAdmin : list) {
			if(dbAdmin.getUsername().equals(admin.getUsername())){
				
				return ResponseResult.build(400, "用户名重复");
			}
	break;
		}
		SystemInfo system = SystemInfo.getInstance();
		String hostName = system.getHostName();
		String ip = system.getIP();

		admin.setLocalhost(ip);
		admin.setSystemname(hostName );
		admin.setCreatetime(new Date());
		admin.setUpdatetime(new Date());
		int n = admapper.insertSelective(admin);
		System.out.println("成功插入了"+n+"条记录到数据库");
		return ResponseResult.ok(n );
	}

	private String getadminItems() {
		// TODO Auto-generated method stub
		try {
		/*	String cookie=CookieUtils.getCookieValue(request, USERNAME);
		
				return cookie;
		*/
			
		String json = SessionUtils.getSessionAttribute(USERNAME).toString();
return json;
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return  null;
		}
		
	}

	private String getSessionByUsername(){
		String username = SessionUtils.getSessionAttribute(USERNAME).toString();
		if(!username.equals("")){
			return username;
		}else{
			
			return "error/404";
		}
	}
	public DbAdmin getDbAdminItems() {
		// TODO Auto-generated method stub
	 String username = getSessionByUsername();

	DbAdminExample example=new DbAdminExample();
	Criteria createCriteria = example.createCriteria();
	createCriteria.andUsernameEqualTo(username);
	List<DbAdmin> selectByExample = admapper.selectByExample(example);
	for (DbAdmin dbAdmin : selectByExample) {
		return dbAdmin;
	}
		return null;
	}

	public ResponseResult addUser(DbAdmin admin) {
		// TODO Auto-generated method stub
		
		
	
		try {
			String realname=admin.getRealname();
			String password = admin.getPassword();
			String md5 = DigestUtils.md5DigestAsHex(password.getBytes());
			SystemInfo system = SystemInfo.getInstance();
			String hostName = system.getHostName();
			String ip = SessionUtils.getIp();
			admin.setRealname(realname);
			admin.setPassword(md5);
			admin.setLocalhost(ip);
			admin.setSystemname(hostName );
			admin.setCreatetime(new Date());
			admin.setUpdatetime(new Date());
			int n= admapper.updateByPrimaryKey(admin);
			System.out.println(n+".................添加成功");
	
				return ResponseResult.ok(); 
			
		} catch (Exception e) {
			// TODO: handle exception
			return ResponseResult.build(400, "添加失败");
		}
		
		
	}
//退出登录
	public ResponseResult LogOut() {
		// TODO Auto-generated method stub
		//CookieUtils.deleteCookie(request, response, USERNAME);
		SessionUtils.removeSessionAttribute(USERNAME);

		realm.clearAllCachedAuthorizationInfo();
		return ResponseResult.ok();
	}

	public ResponseResult insertLogByAdmin() {
		// TODO Auto-generated method stub
		DbAdminlog adminlog=new DbAdminlog();
		//通过session获取用户名
		 //String username = CookieUtils.getCookieValue(request, USERNAME);
		Object sessionAttribute = SessionUtils.getSessionAttribute(USERNAME);
		String username =sessionAttribute.toString();
		
		//获取id
		DbAdminExample example=new DbAdminExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUsernameEqualTo(username);
		List<DbAdmin> list = admapper.selectByExample(example);
		//管理员id
for (DbAdmin dbAdmin : list) {
	 Integer aid = dbAdmin.getAid();
	 String localhost = dbAdmin.getLocalhost();
	 String systemname = dbAdmin.getSystemname();
	 Date addtime = dbAdmin.getCreatetime();
	 adminlog.setAid(aid);
	 adminlog.setComputeraddress(systemname);
	 adminlog.setIp(localhost);
	 adminlog.setLogtime(addtime);
}
int insert = adlogMapper.insert(adminlog);
System.out.println(insert+"...............插入"+insert+"条");
		return ResponseResult.ok();
	}

	public List<ResultAdminLog> selectByAdminlog() {
		// TODO Auto-generated method stub
		//String username = CookieUtils.getCookieValue(request, USERNAME);
		Object sessionAttribute = SessionUtils.getSessionAttribute(USERNAME);
		String username =sessionAttribute.toString();
		DbAdminExample example=new DbAdminExample();
		Criteria createCriteria = example.createCriteria();
		createCriteria .andUsernameEqualTo(username);
		List<DbAdmin> list = admapper.selectByExample(example);
	
		for (DbAdmin dbAdmin : list) {
			Integer adminid = dbAdmin.getAid();
			 List<ResultAdminLog> selectByManyTable = ManagerMapper.selectByManyTable(adminid);
			 			return selectByManyTable;
		
		}
		return null;
	}

	public List<DbAdmin> getDbAdmin() {
		DbAdminExample example=new DbAdminExample ();
		List<DbAdmin> list = admapper.selectByExample(example);
		return list;
	}

	public DbAdmin selAdminById(Integer id) {
		// TODO Auto-generated method stub
		DbAdminExample example=new DbAdminExample ();
		Criteria createCriteria = example.createCriteria();
		createCriteria .andAidEqualTo(id);
		
		List<DbAdmin> list= admapper.selectByExample(example);
		
		return list.get(0);
	}

	

	public DbAdmin selAdminByUserName(String username) {
		// TODO Auto-generated method stub
		DbAdminExample example=new DbAdminExample();
		
		Criteria createCriteria = example.createCriteria();
		createCriteria.andUsernameEqualTo(username);
		return admapper.selectByExample(example).get(0);
	}

	public LayuiResult selAdmins(Integer page, Integer limit) {
		PageHelper.startPage(page, limit);
		DbAdminExample example = new DbAdminExample();
		Criteria criteria = example.createCriteria();
		List<DbAdmin> list = admapper.selectByExample(example);
		// 将roleName写进TbAdmin
		for (DbAdmin tbAdmin : list) {
			// tbAdmin.setRoleName();
			List<DbRoles> roles = roleService.selRoles();
			for (DbRoles tbRole : roles) {
				if (tbRole.getRoleId() == tbAdmin.getRoleId()) {
					tbAdmin.setRoleName(tbRole.getRoleName());
				}
			}
		}
		PageInfo<DbAdmin> pageInfo = new PageInfo<DbAdmin>(list);
		LayuiResult resultUtil = new LayuiResult();
		resultUtil.setCode(0);
		resultUtil.setCount(pageInfo.getTotal());
		resultUtil.setData(pageInfo.getList());
		return resultUtil;
	}

	public Integer delAdminById(Long id) {
		// TODO Auto-generated method stub
		return admapper.deleteByPrimaryKey(id.intValue());
	}

	public void insAdmin(DbAdmin admin) {
		admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
		admapper.insert(admin);
		
	}

	public void updAdmin(DbAdmin admin) {
		DbAdmin a = admapper.selectByPrimaryKey(admin.getAid());
		admin.setPassword(a.getPassword());
		int updateByPrimaryKey = admapper.updateByPrimaryKeySelective(admin);
		System.out.println(updateByPrimaryKey+".....................管理员信息修改成功");
		
	}

	public Integer delAdmins(String adminStr) {
		// TODO Auto-generated method stub
		String[] ids = adminStr.split(",");
		Integer n=0;
		if(ids.length>0&&ids!=null){
			for (String id : ids) {
			n=	admapper.deleteByPrimaryKey(Integer.parseInt(id));
			}
		}
		return n;
	}

	








}
